$(document).ready(function(){
	try{
		$.jgrid.no_legacy_api = true;
		$.jgrid.useJSON = true;
		$.jgrid.formatter.integer.thousandsSeparator = ',';
		$.jgrid.formatter.number.thousandsSeparator = ',';
		$.jgrid.formatter.currency.thousandsSeparator = ',';
		
	    $("#orderItemsTable").jqGrid({                      
	        url : appRoot + '/sampleItem/list/' + sampleId + '?ajax=1',
	        editurl : appRoot + '/sampleItem/save?ajax=1&sampleId=' +sampleId,
	        datatype : 'json',
	        mtype : 'GET',
	        jsonreader: {             
	            repeatitems: false,
	            id:'Id',
	            root:'rows'
	        }, 
	        colNames : [ 'id','objectId','书名', '编号', '数量','单位', '单价', '小计'],
	        colModel : [
	       {
	            name : 'id',
	            index : 'id',
	            editable : true,
	            hidden:true
	            
	        }, {
	            name : 'objectId',
	            index : 'objectId',
	            editable : true,
	            hidden:true
	        },
	        {
	            name : 'bookName',
	            index : 'bookName',
	            width : 300,
	            align : 'left',
	            resizable : false,
	            editable : true,
	            edittype:'text',
	            sortable: false,
	            editrules : {
	                required : true
	            }

	        }, {
	            name : 'no',
	            index : 'no',
	            width : 140,
	            editable : true,
	            edittype:'text',
	            sortable: false,
	            editrules : {
	                required : true
	            }
	        }, {
	            name : 'quantity',
	            index : 'quantity',
	            width : 60,
	            editable : true,
	            align : 'right',
	            edittype:'text',
	            editoptions:{
	                cols:21,rows:3
	            },
	            sortable: false,
	            editrules : {
	                required : true,
	                number : true
	            }
	        }, {
				name : 'unit',
				index : 'unit',
				width : 40,
				editable : true,
				edittype:'select',
				formatter:'select',
				editoptions : {
			        value :units
			    },
				editrules : {
					required : true
				}
			}, {
	            name : 'unitPrice',
	            index : 'unitPrice',
	            width : 60,
	            align : 'right',
	            editable : true,
	            edittype:'text',
	            sortable: false,
	            editrules : {
	                required : true,
	                number : true
	            }                           
	        }, {
	            name : 'amount',
	            index : 'amount',
	            width : 100,
	            align : 'right',
	            editable : false,
	            sortable: false,
	            editrules : {
	                number : true
	            }
	        }
	        ],
	        gridComplete: function(){
	            var grid = $("#orderItemsTable");
	            sumAmount = grid.jqGrid('getCol', 'amount', false, 'sum'); 
	            sumQuantity = grid.jqGrid('getCol', 'quantity', false, 'sum'); 
	            grid.jqGrid('footerData','set', {bookName:"合计:", quantity:sumQuantity,amount: sumAmount}); 
	        },
	        width: 730,
	        height : 200,
	        pager : $('#pager'),
	        nowNum : 100,
	        rowNum : 100,
	        sortname : 'id',
	        viewrecords : true,
	        footerrow: true,
	        shrinkToFit:false,
	        caption : '样品清单'
	    }).navGrid("#pager",{edit:true,add:true,del:true,search:false});
	    
	}catch(e){}
	
    $(".colorbox").colorbox({iframe:true, innerWidth:700, innerHeight:460});
    $(".picture").colorbox();

});
    
    

   fileLimit = 3;
   function createUploader(){
	   var filelimituploader = new qq.FileUploader({
           element: document.getElementById('filelimit-fine-uploader'),
           action: appRoot + '/picture/upload/1/' + sampleId + '?ajax=1',
           debug: true,
           demoMode: false,
           forceMultipart:true,
           allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
           sizeLimit: fileUploadSize,
           uploadButtonText:"上传图片",
           cancelButtonText:"取消",
           failUploadText:"上传失败",
           onSubmit: function(id, fileName) {
        	   sampleFileCount ++;
               if(sampleFileCount > fileLimit) {
                   alert("已经达到最大上传文件数量，不能再上传了！");
                   sampleFileCount--;
                   return false;
               }
           },
           onCancel: function(id, fileName) {
        	   sampleFileCount --;
               if(sampleFileCount <= fileLimit) {
                   $('#filelimit-fine-uploader .qq-upload-button').show();
               }
           },
           onComplete: function(id, fileName, responseJSON) {
               if (responseJSON.success) {
            	   var fileId = responseJSON.fileId;
            	   var fileSuffix = responseJSON.fileSuffix;
            	   var fileName = responseJSON.fileName;
                   $('#filelimit-fine-uploader').append('<div style="float: left;width: 200px;" id="d_f_' + fileId + '"><a href="' + appRoot + '/download/' 
                		    + fileId + fileSuffix + '" title="' + fileName + '" class="picture"><img alt="' + fileName + '" src="' + appRoot + '/download/'
                		    + fileId + fileSuffix + '" width="150">'
                		    + '<a href="javascript:deletePicture(\'' + fileId + '\')">删除</a></div>');
                   $(".picture").colorbox();
               }
           }
       });
	   $(".qq-upload-list").hide();
   }
   
   function deletePicture(fileId){
	   if(fileId){
		   if(confirm("你确定要删除此图片吗？")){
			   $.ajax({
                    url: appRoot + "/picture/delete/" + fileId,
                    type:'post',
                    dataType:'json',
                    success:function(msg){
                        if(msg.success){
                            alert("删除成功");
                            sampleFileCount --;
                            $("#d_f_" + fileId).remove();
                        }
                    }
               });
           }
       }
   }
   
//page
   function getCustomer(id){
       $("#suberror").hide();
       $("#subnotice").hide();
       $("#otherUsers").val("");
       $("input[type='checkbox']").each(function(){
           $(this).attr("checked",false);
       });
       if(id){
           $.ajax({
                url:appRoot + "/customer/get/" + id,
                type:'post',
                dataType:'json',
                success:function(msg){
                    $("#customer_2").text(msg.entity.name).attr("title",msg.entity.email);
                }
           });
       }
   }


  function notify(){
      if(currentOrderId==null){
          return;
      }
      $(".audit").attr("disabled",true);
      $("#notifyButton").attr("disabled",true);
      var selected = getCheckedValuesString(document.getElementsByName("users"));
      var customer = ($("#customer_1").attr("checked")=="checked");
      var others = $("#otherUsers").val();
      if(!selected&&!customer&&!others){
          $("#suberror").html("请至少选择一个接收者").show();
          $(".audit").attr("disabled",false);
          $("#notifyButton").attr("disabled",false);
      }else{
          $("#suberror").hide();
          $("#subnotice").html("操作进行中...").show();
          $.ajax({
               url:appRoot + "/sample/notify/" + currentOrderId + "?date=" + (new Date()).valueOf(),
               type:'post',
               dataType:'json',
               data:'purchasers=' + (selected==null?"":selected) + "&customer=" + customer + "&others=" + others,
               success:function(msg){
                   if(msg.result){
                       showMessage("邮件已发送");
                   }else{
                       showMessage("操作失败");
                   }
                   $(".audit").attr("disabled",false);
                   $("#notifyButton").attr("disabled",false);
                   jQuery.fn.colorbox.close();
               }
          });
      }
  }